﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Runtime.Remoting.Proxies;
using System.Diagnostics;

namespace JAAF.Builders.Configuration
{
    /// <summary>
    /// Implements a <see cref="ConfigurationSection">configuration section</see> for the ObjectFactory implementations and builder declarations
    /// </summary>
    public class BuildersConfigurationSection : ConfigurationSection
    {
        #region Constants

        public static string CONFIG_PROP_IMPLEMENTATIONS = "Implementations";

        public static string CONFIG_SECTION_NAME = "Builders";

        #endregion


        #region Static fields

        private static ConfigurationProperty s_oImplementationsColProp = new ConfigurationProperty(CONFIG_PROP_IMPLEMENTATIONS, typeof(ImplementationRegistrations));

        private static BuildersConfigurationSection s_oCurrentSection;
        private static object s_oCurrSectionSync = new object();
        
        #endregion


        public static BuildersConfigurationSection Current
        {
            get
            {
                try
                {
                    if (s_oCurrentSection == null)
                    {
                        lock(s_oCurrSectionSync)
                        {
                            if (s_oCurrentSection == null)
                            {
                                s_oCurrentSection = (BuildersConfigurationSection)ConfigurationManager.GetSection(CONFIG_SECTION_NAME);
                            }
                        }
                    }

                    return s_oCurrentSection;
                }
                 
                catch (Exception ex)
                {
                    throw new ConfigurationErrorsException("An exception has occured while reading the JAAF - Builders configuration section.", ex);
                }
            }
        }


        /// <summary>
        /// Gets the <see cref="ImplementationRegistration">registrations</see> of concrete implementations of abstractions
        /// (interfaces and base classes).
        /// </summary>
        [ConfigurationProperty("Implementations", IsDefaultCollection=true)]
        public ImplementationRegistrations Implementations
        {
            get
            {
                return (ImplementationRegistrations)base[s_oImplementationsColProp];
            }
        }

    }   
}
